package com.dsl.dslallinone.service;

import com.dsl.dslallinone.common.exception.DslException;
import com.dsl.dslallinone.dto.DslQuery;
import com.dsl.dslallinone.dto.DslQueryResponse;
import com.dsl.dslallinone.dto.Granularity;
import com.dsl.dslallinone.core.DslSqlBuilder;
import com.dsl.dslallinone.core.RealtimeRouter;
import com.dsl.dslallinone.mapper.DslQueryMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DSL查询服务
 */
@Service
public class DslQueryService {
    private static final Logger logger = LoggerFactory.getLogger(DslQueryService.class);

    @Autowired
    private DslSqlBuilder dslSqlBuilder;

    @Autowired
    private RealtimeRouter realtimeRouter;

    /**
     * 执行DSL查询
     */
    public DslQueryResponse executeQuery(DslQuery query) {
        logger.info("开始执行DSL查询");

        // 路由判断：realtime vs fact
        if ("realtime".equals(query.getSource()) || isRealtimeQuery(query)) {
            return executeRealtimeQuery(query);
        } else {
            return executeFactQuery(query);
        }
    }

    /**
     * 判断是否为实时查询
     */
    private boolean isRealtimeQuery(DslQuery query) {
        // 如果是小时粒度且查询当天数据，则认为是实时查询
        return query.getTime().getGranularity() == Granularity.HOUR &&
               query.getTime().getWindow().getStart().equals(query.getTime().getWindow().getEnd());
    }

    /**
     * 执行实时查询
     */
    private DslQueryResponse executeRealtimeQuery(DslQuery query) {
        logger.info("执行实时查询");
        return realtimeRouter.executeQuery(query);
    }

    /**
     * 执行事实表查询
     */
    private DslQueryResponse executeFactQuery(DslQuery query) {
        logger.info("执行事实表查询");

        // 构建SQL
        String sql = dslSqlBuilder.buildSql(query);
        logger.debug("生成SQL: {}", sql);

        // 执行SQL查询
        List<Map<String, Object>> resultData = executeSql(sql);

        // 组装响应
        return buildResponse(query, resultData, "fact");
    }

    @Autowired
    private DslQueryMapper dslQueryMapper;

    /**
     * 执行SQL查询
     */
    private List<Map<String, Object>> executeSql(String sql) {
        logger.debug("执行SQL查询: {}", sql);

        try {
            return dslQueryMapper.executeDynamicSql(sql);
        } catch (Exception e) {
            logger.error("SQL执行失败: {}", e.getMessage(), e);
            throw new DslException("查询执行失败: " + e.getMessage());
        }
    }

    /**
     * 构建响应数据
     */
    private DslQueryResponse buildResponse(DslQuery query, List<Map<String, Object>> data, String dataSource) {
        // 构建series数据
        List<DslQueryResponse.SeriesData> series = buildSeriesData(data, query);

        // 构建table数据
        DslQueryResponse.TableData table = buildTableData(data);

        // 构建meta数据
        DslQueryResponse.MetaData meta = new DslQueryResponse.MetaData(
                query.getTime().getGranularity(),
                query.getTime().getWindow(),
                getUnit(query),
                dataSource
        );

        return new DslQueryResponse(series, table, meta);
    }

    /**
     * 构建时间序列数据
     */
    private List<DslQueryResponse.SeriesData> buildSeriesData(List<Map<String, Object>> data, DslQuery query) {
        List<DslQueryResponse.SeriesData> series = new ArrayList<>();
        
        // 简化实现：按第一个维度分组
        if (query.getGroupBy() != null && !query.getGroupBy().isEmpty()) {
            String groupField = query.getGroupBy().get(0);
            Map<String, List<Map<String, Object>>> grouped = new HashMap<>();
            
            for (Map<String, Object> row : data) {
                String key = String.valueOf(row.get(groupField));
                grouped.computeIfAbsent(key, k -> new ArrayList<>()).add(row);
            }
            
            for (Map.Entry<String, List<Map<String, Object>>> entry : grouped.entrySet()) {
                series.add(new DslQueryResponse.SeriesData(
                        groupField + "=" + entry.getKey(),
                        entry.getValue()
                ));
            }
        } else {
            series.add(new DslQueryResponse.SeriesData("default", data));
        }
        
        return series;
    }

    /**
     * 构建表格数据
     */
    private DslQueryResponse.TableData buildTableData(List<Map<String, Object>> data) {
        if (data.isEmpty()) {
            return new DslQueryResponse.TableData(new ArrayList<>(), new ArrayList<>());
        }

        // 获取列名
        List<String> columns = new ArrayList<>(data.get(0).keySet());

        // 构建行数据
        List<List<Object>> rows = new ArrayList<>();
        for (Map<String, Object> row : data) {
            List<Object> rowData = new ArrayList<>();
            for (String column : columns) {
                rowData.add(row.get(column));
            }
            rows.add(rowData);
        }

        return new DslQueryResponse.TableData(columns, rows);
    }

    /**
     * 获取单位
     */
    private String getUnit(DslQuery query) {
        // 从第一个metric获取单位
        if (query.getMetrics() != null && !query.getMetrics().isEmpty()) {
            return query.getMetrics().get(0).getUnit();
        }
        return null;
    }
}
